package com.jeefw.cloud.httpdoc.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.jeefw.cloud.httpdoc.dao.entities.Httpdoc;
import com.jeefw.cloud.httpdoc.repository.HttpdocRepository;
import com.jeefw.cloud.httpdoc.service.HttpdocIndexService;

@RestController
@RequestMapping("/httpdoc/")
public class HttpdocController {

	@Autowired
	private HttpdocRepository userRepository;
	
	@Autowired
	protected HttpdocIndexService httpdocIndexService;

	@Autowired
	private EurekaClient eurekaClient;

	@Autowired
	private DiscoveryClient discoveryClient;

	@GetMapping("/index/{id}")
	public Httpdoc index(@PathVariable Integer id) {
		return this.httpdocIndexService.get(id);
	}
	
	@GetMapping("/simple/{id}")
	public Httpdoc findById(@PathVariable Long id) {
		return this.userRepository.findOne(id);
	}

	@GetMapping("/eureka-instance")
	public String serviceUrl() {
		InstanceInfo instance = this.eurekaClient.getNextServerFromEureka("MICROSERVICE-PROVIDER-USER", false);
		return instance.getHomePageUrl();
	}

	@GetMapping("/instance-info")
	public ServiceInstance showInfo() {
		ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();
		return localServiceInstance;
	}

	@PostMapping("/user")
	public Httpdoc postUser(@RequestBody Httpdoc user) {
		return user;
	}

	// 该请求不会成功
	@GetMapping("/get-user")
	public Httpdoc getUser(Httpdoc user) {
		return user;
	}

	@GetMapping("list-all")
	public List<Httpdoc> listAll() {
		ArrayList<Httpdoc> list = Lists.newArrayList();
		Httpdoc user = new Httpdoc(1L, "zhangsan");
		Httpdoc user2 = new Httpdoc(2L, "zhangsan");
		Httpdoc user3 = new Httpdoc(3L, "zhangsan");
		list.add(user);
		list.add(user2);
		list.add(user3);
		return list;

	}
}
